/**
 * A simple IDomainSpecificApi implementation that creates tasks from the
 * package named by the parameter passed to the constructor, or added via
 * addPackage(). The class loader used to load the task classes is passed in as
 * the first argument to all constructors. If the object is passed into the
 * constructor is not a class loader, the class loader for that object's class
 * will be used.
 */
package com.googlecode.lightest.core

import com.googlecode.lightest.core.IDomainSpecificApi
import com.googlecode.lightest.core.ITask

class SimpleApi implements IDomainSpecificApi {
    def classLoader
    def packages
    
    SimpleApi(ClassLoader classLoader) {
        this.classLoader = classLoader
        packages = [ "" ]
    }
    
    SimpleApi(GroovyObject object) {
        this(object.class.classLoader)
    }
    
    SimpleApi(GroovyObject object, String packageName) {
        this(object.class.classLoader, packageName)
    }
    
    SimpleApi(ClassLoader classLoader, String packageName) {
        this(classLoader)
        addPackage(packageName)
    }
    
    /**
     * Adds another package whose tasks to include in the API.
     */
    void addPackage(String packageName) {
        packages << packageName
    }
    
    /**
     * Creates and returns a task as a class in the specified package.
     *
     * @param name  the name of the task, which is also the name of its
     *              corresponding class
     */
    ITask getTask(String name) {
        for (packageName in packages) {
            def qname = packageName ? "${packageName}.${name}" : name
            def taskClass
                    
            try {
                taskClass = classLoader.loadClass(qname)
            }
            catch (ClassNotFoundException cnfe) {
                continue
            }
            
            def task = taskClass.newInstance()
            if (task instanceof ITask) {
                return task
            }
        }
        return null
    }
}